const productModel = require('../models/productModel');
const jwt = require('jsonwebtoken');
require('dotenv').config();  // 确保加载 .env 文件


// 获取所有商品
const getAllProducts = async (req, res) => {
    try {
        const products = await productModel.getAllProducts();
        res.json({ success: true, data: products });
    } catch (error) {
        console.error('Error fetching products:', error);
        res.status(500).json({ success: false, message: 'Error fetching products', error: error.message });
    }
};
// 获取当前用户所有商品
const getProductsByUserId = async (req, res) => {
    const token = req.headers.authorization?.split(' ')[1];  // 获取请求头中的 JWT token

    if (!token) {
        return res.status(403).json({ success: false, message: '未授权访问' });
    }
    // console.log('Token:', token);
    try {
        // 验证 JWT token 获取用户 ID
        const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY);  // 解码 token 获取 user_id
        // console.log('Decoded token:', decoded);
        const userId = decoded.id;
        // console.log('User ID:', userId);  // 打印用户 ID，用于调试

        // 调用 model 获取当前用户的所有商品
        const products = await productModel.getProductsByUserId(userId);
        // console.log('Products:', products);  // 打印商品信息，用于调试

        if (products.length > 0) {
            res.json({ success: true, data: products });
        } else {
            res.status(404).json({ success: false, message: '该用户没有商品或商品未找到' });
        }
    } catch (error) {
        res.status(500).json({ success: false, message: '获取商品失败', error: error.message });
    }
};

// 添加商品
const addProduct = async (req, res) => {
    const { name, description, price, stock, category, image_url } = req.body;
    // console.log('Request body:', req.body); // 获取商品信息
    const userId = req.user.id;  // 从请求的用户信息中获取当前用户的 ID
    // console.log( req.user)
    if (!name || !description || !price || !stock || !category || !image_url) {
        return res.status(400).json({ success: false, message: "All fields are required" });
    }

    try {
        const productId = await productModel.addProduct({ name, description, price, stock, category, image_url }, userId);
        res.status(201).json({ success: true, productId, message: '商品添加成功' });
    } catch (error) {
        res.status(500).json({ success: false, message: '添加失败', error: error.message });
    }
};


// 获取商品详情
const getProductById = async (req, res) => {
    const { productId } = req.params;  // 获取 URL 参数中的商品 ID

    try {
        // 从数据库获取商品详情
        const product = await productModel.getProductById(productId);

        if (product) {
            res.json({ success: true, data: product });
        } else {
            res.status(404).json({ success: false, message: '商品未找到' });
        }
    } catch (error) {
        console.error('Error fetching product by ID:', error);
        res.status(500).json({ success: false, message: '获取商品详情失败', error: error.message });
    }
};


// 更新商品
const updateProduct = async (req, res) => {
    const { productId } = req.params;  // 从 URL 参数中获取商品 ID
    // console.log(productId)
    const { name, description, price, stock, category, image_url } = req.body;  // 获取更新的商品信息和图片 URLs
    const token = req.headers.authorization?.split(' ')[1];  // 获取请求头中的 JWT token
    // console.log(req.body)

    if (!token) {
        return res.status(403).json({ success: false, message: '未授权访问' });
    }

    try {
        // 验证 JWT token 获取用户 ID
        const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY);
        const userId = decoded.id;
        // console.log(userId)

        // 首先检查商品是否属于当前用户
        const product = await productModel.getProductsByUserId(productId, userId);
        if (!product) {
            return res.status(404).json({ success: false, message: '商品未找到或没有权限更新该商品' });
        }

        // 如果商品属于当前用户，执行更新
        await productModel.updateProduct(productId, { name, description, price, stock, category, user_id: userId }, image_url);
        res.json({ success: true, message: '商品更新成功', urls: image_url });

    } catch (error) {
        console.error(error);
        res.status(500).json({ success: false, message: '商品更新失败', error: error.message });
    }
};

// 退款
const product = async (req, res) => {
    const { productId } = req.params;  // 从 URL 参数中获取商品 ID
    console.log(productId + "eiieo")
    try {
        const product = await productModel.setproduct(productId);
        console.log(product, "我的");
        if (product) {
            res.json({ success: true, code: 200 });
        } else {
            res.json({ success: false, message: '退款失败' });
        }

    } catch (error) {
        console.log(error)
    }
};
// 取消拼团
const cancelGroupBuy = async (req, res) => {

    console.log(req.params);
    
    const { productId } = req.params;
    try {
        const result = await productModel.cancelGroupBuy(productId);
        if (result.affectedRows > 0) {
            res.json({ success: true, message: '拼团已取消' });
        } else {
            res.status(400).json({ success: false, message: '拼团取消失败或拼团已被处理' });
        }
    }catch (error) {
        res.status(500).json({ success: false, message: '拼团取消失败', error });
    }
};

// 删除商品
const deleteProductController = async (req, res) => {
    const { productId } = req.params;
    try {
        const result = await productModel.deleteProduct(productId);  // 调用删除操作
        if (result.affectedRows > 0) {  // 判断删除是否成功
            res.json({ success: true, message: '商品删除成功' });
        } else {
            res.status(404).json({ success: false, message: '商品未找到' });
        }
    } catch (error) {
        console.error('Error in deleting product:', error);
        res.status(500).json({ success: false, message: '删除商品失败', error: error.message });
    }
};
// 获取商品分类的商品
const getProductsByCategory = async (req, res) => {
    const { category } = req.params;
    console.log('Requested category:', category);  // 打印请求的分类

    try {
        const products = await productModel.getProductsByCategory(category);
        console.log('Fetched products:', products);  // 打印返回的商品数据

        if (products.length === 0) {
            // 如果没有商品，返回空数组和 200 状态
            return res.status(200).json([]);  // 不是 404，而是返回空数组
        }
        res.status(200).json(products);
    } catch (err) {
        console.error('Error fetching products:', err);  // 打印具体错误信息
        res.status(500).json({ error: 'Failed to fetch products' });
    }
};





// 获取拼团活动信息
const getGroupBuyInfo = async (req, res) => {
    try {
        const { product_id, user_id } = req.query;

        if (!user_id) {
            return res.status(400).json({ message: '用户ID是必需的' });
        }

        const groupBuyData = await productModel.getGroupBuyStatus(product_id, user_id);

        if (!groupBuyData) {
            return res.status(404).json({ message: '没有找到拼团活动' });
        }

        res.json(groupBuyData);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '服务器错误' });
    }
};

// 发起拼团活动
const startGroupBuy = async (req, res) => {
    console.log(req.body);

    try {
        const { product_id, user_id, end_time } = req.body;
        console.log(user_id);
        const row = await productModel.getProd(user_id, product_id)
        if (row.length > 0) {

            return res.json({ code: 200, message: '该用户已发起拼团' });
        } else {
            // const groupbuy_id = await productModel.startGroupBuy(product_id, user_id, end_time);
            res.status(201).json({
                success: true,
                message: '拼团活动已成功发起',

            });
        }




        // 调用模型函数发起拼团活动
        // 


    } catch (error) {
        console.error('发起拼团失败:', error);
        res.status(500).json({ message: '发起拼团活动失败' });
    }
};
const startGroupBuy2 = async (req, res) => {
    console.log(req.body);

    try {
        const { product_id, user_id, end_time } = req.body;
        console.log(user_id);

        const groupbuy_id = await productModel.startGroupBuy(product_id, user_id, end_time);
        res.status(201).json({
            success: true,
            message: '拼团活动已成功发起',
        });

    } catch (error) {
        console.error('发起拼团失败:', error);
        res.status(500).json({ message: '发起拼团活动失败' });
    }
};

// // 用户加入拼团
const joinGroupBuy = async (req, res) => {
    try {
        const { groupbuy_id, user_id } = req.body;
        const row = await productModel.getProd2(user_id, groupbuy_id)
        if (row.length > 0) {
            return res.json({ code: 200, message: '该用户已加入拼团' });
        } else {

            // 调用模型函数处理加入拼团
            const result = await productModel.joinGroupBuy(groupbuy_id, user_id);

            res.json({ message: '成功加入拼团', success: true });
        }
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
};


// 获取拼团参与者
const getParticipants = async (req, res) => {
    try {
        const { groupbuy_id } = req.query;

        if (!groupbuy_id) {
            return res.status(400).json({ message: '拼团ID是必需的' });
        }

        // 获取参与者
        const participants = await productModel.getParticipants(groupbuy_id);

        res.json({ participants });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '获取参与者失败' });
    }
};


module.exports = {
    getGroupBuyInfo,
    startGroupBuy,
    joinGroupBuy,
    getParticipants,
    getAllProducts,
    getProductsByUserId,
    getProductById,
    addProduct,
    startGroupBuy2,
    updateProduct,
    deleteProductController,
    getProductsByCategory,
    product,
    cancelGroupBuy
};
